package com.xianyun.common.core.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import com.alibaba.cola.exception.BizException;
import org.apache.commons.codec.binary.Base64;
import java.nio.charset.StandardCharsets;

/**
 * 字符串加密
 * @author mac_zyj
 */
public class EncryptUtils {
    /**128 bit key*/
    private static final String KEY = "TE53DAH32R9VMHEP";
    /**16 bytes vector*/
    private static final String INIT_VECTOR = "ZEM84JFYEJDHMKG0";

    /**
     * AES 加密<br>
     * 传入需要加密的原文
     *
     * @param strSource 需要加密的原文
     * @return 加密结果
     */
    public static String encrypt(String strSource)
    {
        String strResult = null;
        try
        {
            IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR.getBytes(StandardCharsets.UTF_8));
            SecretKeySpec skewySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");

            Cipher cipher = Cipher.getInstance("AES / GCM / NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, skewySpec, iv);

            byte[] encrypted = cipher.doFinal(strSource.getBytes());
            return Base64.encodeBase64String(encrypted);
        }
        catch (Exception e)
        {
            //TODO 添加加密异常定义
            throw new BizException("加密失败");
        }
    }

    /**
     * AES 解密<br>
     * 输入密文
     *
     * @param encrypted 需要解密的内容
     * @return 解密结果
     */
    public static String decrypt(String encrypted)
    {
        try
        {
            IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR.getBytes(StandardCharsets.UTF_8));
            SecretKeySpec skySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");

            Cipher cipher = Cipher.getInstance("AES / GCM / NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, skySpec, iv);

            byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));

            return new String(original);
        }
        catch (Exception ex)
        {
            //TODO 添加解密异常定义
            throw new BizException("解密失败");
        }
    }

}
